<template>
  <div class="video-player" v-if="show">
    <!-- 小屏播放模式 -->
    <div v-if="!isFullscreen" class="video-player-small" :class="{ 'video-player-modal': showModal }">
      <div class="video-container">
        <video 
          ref="videoElement"
          :src="videoUrl" 
          :poster="effectivePoster"
          @loadedmetadata="onVideoLoaded"
          @play="onPlay"
          @pause="onPause"
          @ended="onEnded"
          @timeupdate="onTimeUpdate"
          @error="onError"
          preload="metadata"
        ></video>
        
        <!-- 缩略图生成中提示 -->
        <div v-if="posterGenerating" class="thumbnail-loading">
          <div class="loading-spinner"></div>
          <span>生成视频封面中...</span>
        </div>
        
        <!-- 视频控制层 -->
        <div class="video-controls" :class="{ 'show': showControls }">
          <div class="control-bar">
            <!-- 播放/暂停按钮 -->
            <button class="control-btn play-btn" @click="togglePlay">
              <span v-if="isPlaying">⏸</span>
              <span v-else>▶</span>
            </button>
            
            <!-- 进度条 -->
            <div class="progress-container">
              <div class="progress-bar" @click="seekTo">
                <div class="progress-filled" :style="{ width: progressPercent + '%' }"></div>
                <div class="progress-handle" :style="{ left: progressPercent + '%' }"></div>
              </div>
            </div>
            
            <!-- 时间显示 -->
            <div class="time-display">
              {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
            </div>
            
            <!-- 音量控制 -->
            <div class="volume-control">
              <button class="control-btn volume-btn" @click="toggleMute">
                <span v-if="isMuted || volume === 0">🔇</span>
                <span v-else-if="volume < 0.5">🔉</span>
                <span v-else>🔊</span>
              </button>
              <div class="volume-slider">
                <input 
                  type="range" 
                  min="0" 
                  max="1" 
                  step="0.1" 
                  v-model="volume" 
                  @input="updateVolume"
                />
              </div>
            </div>
            
            <!-- 全屏按钮 -->
            <button class="control-btn fullscreen-btn" @click="toggleFullscreen">
              <span v-if="isFullscreen">⛶</span>
              <span v-else>⛶</span>
            </button>
            
            <!-- 关闭按钮（小屏模式） -->
            <button v-if="showModal" class="control-btn close-btn" @click="closePlayer">
              ✕
            </button>
          </div>
        </div>
        
        <!-- 加载指示器 -->
        <div v-if="isLoading" class="loading-indicator">
          <div class="spinner"></div>
          <span>加载中...</span>
        </div>
        
        <!-- 错误提示 -->
        <div v-if="hasError" class="error-message">
          <span>视频加载失败</span>
          <button @click="retryLoad">重试</button>
        </div>
      </div>
    </div>
    
    <!-- 全屏播放模式 -->
    <div v-if="isFullscreen" class="video-player-fullscreen">
      <div class="video-container-fullscreen">
        <video 
          ref="videoElementFullscreen"
          :src="videoUrl" 
          :poster="posterUrl"
          @loadedmetadata="onVideoLoaded"
          @play="onPlay"
          @pause="onPause"
          @ended="onEnded"
          @timeupdate="onTimeUpdate"
          @error="onError"
          preload="metadata"
          controls
        ></video>
        
        <!-- 全屏控制层 -->
        <div class="fullscreen-controls" :class="{ 'show': showControls }">
          <button class="control-btn exit-fullscreen-btn" @click="exitFullscreen">
            ⛶ 退出全屏
          </button>
        </div>
      </div>
    </div>
    
    <!-- 遮罩层 -->
    <div v-if="showModal && !isFullscreen" class="video-modal-overlay" @click="closePlayer"></div>
  </div>
</template>

<script>
import { generateVideoThumbnailWithCache } from '../utils/videoUtils.js'

export default {
  name: 'VideoPlayer',
  props: {
    videoUrl: {
      type: String,
      required: true
    },
    posterUrl: {
      type: String,
      default: ''
    },
    autoplay: {
      type: Boolean,
      default: false
    },
    showModal: {
      type: Boolean,
      default: false
    },
    useVideoThumbnail: {
      type: Boolean,
      default: true
    },
    thumbnailTime: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {
      show: false,
      isPlaying: false,
      isFullscreen: false,
      showControls: true,
      currentTime: 0,
      duration: 0,
      volume: 1,
      isMuted: false,
      isLoading: true,
      hasError: false,
      controlsTimeout: null,
      generatedPoster: null,
      posterGenerating: false
    }
  },
  computed: {
    progressPercent() {
      if (this.duration === 0) return 0
      return (this.currentTime / this.duration) * 100
    },
    currentVideoElement() {
      return this.isFullscreen ? this.$refs.videoElementFullscreen : this.$refs.videoElement
    },
    effectivePoster() {
      if (this.useVideoThumbnail && this.generatedPoster) {
        return this.generatedPoster
      }
      return this.posterUrl
    }
  },
  mounted() {
    this.show = true
    this.$nextTick(() => {
      this.initializeVideo()
      if (this.useVideoThumbnail && this.videoUrl) {
        this.generatePoster()
      }
    })
  },
  beforeUnmount() {
    this.cleanup()
  },
  methods: {
    initializeVideo() {
      const video = this.currentVideoElement
      if (video) {
        video.volume = this.volume
        if (this.autoplay) {
          video.play().catch(err => {
            console.warn('自动播放失败:', err)
          })
        }
        this.setupControlsAutoHide()
      }
    },
    
    togglePlay() {
      const video = this.currentVideoElement
      if (video) {
        if (this.isPlaying) {
          video.pause()
        } else {
          video.play().catch(err => {
            console.error('播放失败:', err)
            this.hasError = true
          })
        }
      }
    },
    
    toggleFullscreen() {
      if (this.isFullscreen) {
        this.exitFullscreen()
      } else {
        this.enterFullscreen()
      }
    },
    
    enterFullscreen() {
      this.isFullscreen = true
      this.$nextTick(() => {
        const video = this.$refs.videoElementFullscreen
        if (video) {
          // 同步播放状态
          video.currentTime = this.currentTime
          video.volume = this.volume
          video.muted = this.isMuted
          if (this.isPlaying) {
            video.play()
          }
          
          // 请求全屏
          if (video.requestFullscreen) {
            video.requestFullscreen()
          } else if (video.webkitRequestFullscreen) {
            video.webkitRequestFullscreen()
          } else if (video.msRequestFullscreen) {
            video.msRequestFullscreen()
          }
        }
      })
    },
    
    exitFullscreen() {
      this.isFullscreen = false
      
      // 退出浏览器全屏
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
      }
      
      this.$nextTick(() => {
        const video = this.$refs.videoElement
        if (video) {
          // 同步播放状态
          video.currentTime = this.currentTime
          video.volume = this.volume
          video.muted = this.isMuted
          if (this.isPlaying) {
            video.play()
          }
        }
      })
    },
    
    seekTo(event) {
      const progressBar = event.currentTarget
      const rect = progressBar.getBoundingClientRect()
      const percent = (event.clientX - rect.left) / rect.width
      const seekTime = percent * this.duration
      
      const video = this.currentVideoElement
      if (video) {
        video.currentTime = seekTime
      }
    },
    
    toggleMute() {
      const video = this.currentVideoElement
      if (video) {
        this.isMuted = !this.isMuted
        video.muted = this.isMuted
      }
    },
    
    updateVolume() {
      const video = this.currentVideoElement
      if (video) {
        video.volume = this.volume
        this.isMuted = this.volume === 0
        video.muted = this.isMuted
      }
    },
    
    closePlayer() {
      this.show = false
      this.$emit('close')
    },
    
    retryLoad() {
      this.hasError = false
      this.isLoading = true
      const video = this.currentVideoElement
      if (video) {
        video.load()
      }
    },
    
    setupControlsAutoHide() {
      const container = this.isFullscreen ? 
        document.querySelector('.video-player-fullscreen') : 
        document.querySelector('.video-player-small')
      
      if (container) {
        container.addEventListener('mousemove', this.showControlsTemporarily)
        container.addEventListener('mouseleave', this.hideControls)
      }
    },
    
    showControlsTemporarily() {
      this.showControls = true
      if (this.controlsTimeout) {
        clearTimeout(this.controlsTimeout)
      }
      this.controlsTimeout = setTimeout(() => {
        if (this.isPlaying) {
          this.showControls = false
        }
      }, 3000)
    },
    
    hideControls() {
      if (this.isPlaying) {
        this.showControls = false
      }
    },
    
    cleanup() {
      if (this.controlsTimeout) {
        clearTimeout(this.controlsTimeout)
      }
    },
    
    formatTime(seconds) {
      if (isNaN(seconds)) return '00:00'
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    },
    
    // 视频事件处理
    onVideoLoaded() {
      const video = this.currentVideoElement
      if (video) {
        this.duration = video.duration
        this.isLoading = false
      }
    },
    
    onPlay() {
      this.isPlaying = true
      this.hasError = false
    },
    
    onPause() {
      this.isPlaying = false
    },
    
    onEnded() {
      this.isPlaying = false
      this.currentTime = 0
      this.$emit('ended')
    },
    
    onTimeUpdate() {
      const video = this.currentVideoElement
      if (video) {
        this.currentTime = video.currentTime
      }
    },
    
    onError() {
      this.hasError = true
      this.isLoading = false
      console.error('视频加载错误')
    },
    
    // 生成视频缩略图
    async generatePoster() {
      if (!this.videoUrl || this.posterGenerating) {
        return
      }
      
      try {
        this.posterGenerating = true
        const thumbnail = await generateVideoThumbnailWithCache(
          this.videoUrl,
          this.thumbnailTime
        )
        this.generatedPoster = thumbnail
      } catch (error) {
        console.warn('生成视频缩略图失败:', error)
        // 失败时保持使用原始poster
      } finally {
        this.posterGenerating = false
      }
    }
  }
}
</script>

<style scoped>
.video-player {
  position: relative;
  z-index: 1000;
}

/* 小屏播放模式 */
.video-player-small {
  position: relative;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.video-player-modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1001;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
}

.video-container {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%; /* 16:9 宽高比 */
}

.video-container video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 全屏播放模式 */
.video-player-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: #000;
  z-index: 1002;
}

.video-container-fullscreen {
  position: relative;
  width: 100%;
  height: 100%;
}

.video-container-fullscreen video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 视频控制层 */
.video-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 20px 15px 15px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.video-controls.show {
  opacity: 1;
}

.control-bar {
  display: flex;
  align-items: center;
  gap: 15px;
}

.control-btn {
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.control-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.play-btn {
  font-size: 18px;
}

.progress-container {
  flex: 1;
  margin: 0 10px;
}

.progress-bar {
  position: relative;
  height: 6px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
  cursor: pointer;
}

.progress-filled {
  height: 100%;
  background: #ff6b6b;
  border-radius: 3px;
  transition: width 0.1s;
}

.progress-handle {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 12px;
  height: 12px;
  background: #ff6b6b;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.2s;
}

.progress-bar:hover .progress-handle {
  opacity: 1;
}

.time-display {
  color: white;
  font-size: 14px;
  min-width: 100px;
  text-align: center;
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.volume-slider input {
  width: 60px;
}

.close-btn {
  font-size: 20px;
  margin-left: auto;
}

/* 全屏控制层 */
.fullscreen-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.fullscreen-controls.show {
  opacity: 1;
}

.exit-fullscreen-btn {
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

/* 加载指示器 */
.loading-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  color: white;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 错误提示 */
.error-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  color: white;
  text-align: center;
}

.error-message button {
  background: #ff6b6b;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

/* 遮罩层 */
.video-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.8);
  z-index: 1000;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-player-modal {
    width: 95vw;
    max-width: none;
  }
  
  .control-bar {
    gap: 10px;
  }
  
  .time-display {
    font-size: 12px;
    min-width: 80px;
  }
}

/* 视频缩略图加载样式 */
.thumbnail-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  background: rgba(0, 0, 0, 0.8);
  padding: 15px 20px;
  border-radius: 8px;
  color: white;
  font-size: 12px;
  z-index: 15;
}

.thumbnail-loading .loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid #4ecdc4;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.thumbnail-loading span {
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.volume-control {
  display: none;
}
</style>